<template>
    <div
        :class="['w-full text-20 p-24 box-border', { 'min-loading-height': isLoading }]"
        v-loading="isLoading"
        element-loading-text="加载中....."
    >
        <template v-if="!isLoading">
            <PageHeader :show-refresh="false" :title="PageType[pageType]">
                <template #custom>
                    <!-- 查看模式 - 只有返回按钮 -->
                    <template v-if="isDisabled">
                        <el-button round type="primary" @click="router.back()">返回</el-button>
                    </template>
                    <!-- 新增模式 - 返回、保存草稿、确认发布 -->
                    <template v-if="pageType !== 'see'">
                        <el-button round @click="router.back()">取消</el-button>
                        <el-button round type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
                    </template>
                </template>
            </PageHeader>
            <!-- 表单 -->
            <el-form
                class="flex-between-box"
                ref="ruleFormRef"
                :model="ruleForm"
                :rules="rules"
                size="default"
                :disabled="isDisabled"
                label-width="110px"
                status-icon
            >
                <!-- 基本信息 -->
                <div class="add-edit-container h-full">
                    <div class="w-h-full card-style common-shadow">
                        <div class="card-title mb-30">基本信息</div>
                        <!-- 商品名称-->
                        <el-form-item label="商品名称：" prop="goodsName">
                            <el-col :span="16">
                                <el-input maxlength="100" placeholder="请输入商品名称..." v-model="ruleForm.goodsName"/>
                            </el-col>
                        </el-form-item>
                        <!-- 商品简介 -->
                        <el-form-item label="商品简介：" prop="goodsDesc">
                            <el-col :span="18">
                                <el-input
                                    :rows="4"
                                    maxlength="100"
                                    show-word-limit
                                    placeholder="描述一下商品信息吧..."
                                    v-model="ruleForm.goodsDesc"
                                    type="textarea"
                                />
                            </el-col>
                        </el-form-item>
                        <!-- 商品卖点 -->
                        <el-form-item label="商品卖点：" prop="goodsPoints">
                            <el-col :span="16" class="mr-10">
                                <el-input placeholder="商品卖点, 多个卖点请使用逗号分割！" v-model="ruleForm.goodsPoints" />
                            </el-col>
                        </el-form-item>
                        <!-- 商品分类 -->
                        <el-form-item label="商品分类：" prop="goodsClassId">
                            <el-select v-model="ruleForm.goodsClassId" placeholder="请选择商品分类">
                                <el-option
                                    v-for="item in goodsClassList"
                                    :key="item.goodsClassId"
                                    :label="item.goodsClassName"
                                    :value="item.goodsClassId"
                                />
                            </el-select>
                        </el-form-item>
                        <!-- 商品图 -->
                        <el-form-item label="商品图：" prop="goodsImageList">
                            <el-upload
                                v-model:file-list="ruleForm.goodsImageList"
                                :action="uploadImgURL"
                                :disabled="isDisabled"
                                list-type="picture-card"
                                :on-preview="handlePictureCardPreview"
                            >
                                <Icon name="Plus"/>
                            </el-upload>
                        </el-form-item>
                    </div>
                    <!-- 物流与其他 -->
                    <div class="specification-logistics card-style mt-24 common-shadow">
                        <div class="card-title mb-30">物流与其他</div>
                        <!-- 配送方式 -->
                        <el-form-item label="配送方式：" prop="goodsDelivery">
                            <el-col :span="6" class="mr-10">
                                <el-select v-model="ruleForm.goodsDelivery" placeholder="请选择配送方式">
                                    <el-option
                                        v-for="({ label, value }) in deliveryMethods"
                                        :key="value"
                                        :label="label"
                                        :value="value"
                                    />
                                </el-select>
                            </el-col>
                        </el-form-item>
                        <!-- 快递运费 -->
                        <el-form-item label="快递运费：" prop="isNeedFreight">
                            <el-switch v-model="ruleForm.isNeedFreight"/>
                            <template v-if="ruleForm.isNeedFreight">
                                <el-col :span="6" class="ml-10">
                                    <div :class="['flex-items-box', labelColor]">
                                        <el-input type="number" placeholder="请输入运费" v-model="ruleForm.expressFreight" /> （元）
                                    </div>
                                </el-col>
                            </template>
                        </el-form-item>
                        <!-- 是否限购 -->
                        <el-form-item label="是否限购：" prop="isLimitBuy">
                            <el-switch v-model="ruleForm.isLimitBuy"/>
                            <template v-if="ruleForm.isLimitBuy">
                                <el-col :span="6" class="ml-10">
                                    <div :class="['flex-items-box', labelColor]">
                                        <el-input type="number" placeholder="请输入限购量" v-model="ruleForm.limitBuyNum" /> （件）
                                    </div>
                                </el-col>
                            </template>
                        </el-form-item>
                        <!-- 上架时间 -->
                        <el-form-item label="上架时间：" prop="listingType">
                            <el-radio-group v-model="ruleForm.listingType">
                                <el-radio :label="1">立即上架</el-radio>
                                <el-radio :label="2">延时上架</el-radio>
                            </el-radio-group>
                            <template v-if="ruleForm.listingType === 2">
                                <el-col :span="10" class="ml-20">
                                    <el-date-picker class="w-full" v-model="ruleForm.listingTime" type="datetime"/>
                                </el-col>
                            </template>
                        </el-form-item>
                    </div>
                </div>
                <!-- 右侧 -->
                <div class="add-edit-container h-full flex-col-between-box">
                    <!-- 商品详情 -->
                    <div class="w-full card-style common-shadow">
                        <div class="card-title mb-30">商品详情</div>
                        <RichText v-model="ruleForm.goodsDetail" :setting="setting" />
                    </div>
                    <!-- 规格信息 -->
                    <div class="specification-logistics mt-24 card-style common-shadow">
                        <div class="card-title mb-30">规格信息</div>
                        <!-- 售价 -->
                        <el-form-item label="售价：" prop="goodsPrice">
                            <el-col :span="8" class="mr-10">
                                <div :class="['flex-items-box', labelColor]">
                                    <el-input type="number" placeholder="请输入商品售价" v-model="ruleForm.goodsPrice" /> （元）
                                </div>
                            </el-col>
                        </el-form-item>
                        <!-- 库存 -->
                        <el-form-item label="库存：" prop="goodsStock">
                            <el-col :span="8" class="mr-10">
                                <div :class="['flex-items-box', labelColor]">
                                    <el-input type="number" placeholder="请输入商品库存" v-model="ruleForm.goodsStock" /> （件）
                                </div>
                            </el-col>
                        </el-form-item>
                        <!-- 划线价 -->
                        <el-form-item label="划线价：" prop="goodsOriginalPrice">
                            <el-col :span="8" class="mr-10">
                                <div :class="['flex-items-box', labelColor]">
                                    <el-input type="number" placeholder="请输入商品划线价" v-model="ruleForm.goodsOriginalPrice" /> （元）
                                </div>
                            </el-col>
                        </el-form-item>
                        <!-- 尺寸 -->
                        <el-form-item label="尺寸：" prop="goodsSize">
                            <el-col :span="5" class="mr-10">
                                <div :class="['flex-items-box', labelColor]">
                                    <el-input type="number" placeholder="长度" v-model="ruleForm.goodsLength" /> （cm）
                                </div>
                            </el-col>
                            <el-col :span="5" class="mr-10">
                                <div :class="['flex-items-box', labelColor]">
                                    <el-input type="number" placeholder="宽度" v-model="ruleForm.goodsWidth" /> （cm）
                                </div>
                            </el-col>
                            <el-col :span="5">
                                <div :class="['flex-items-box', labelColor]">
                                    <el-input type="number" placeholder="高度" v-model="ruleForm.goodsHeight" /> （cm）
                                </div>
                            </el-col>
                        </el-form-item>
                        <!-- 重量 -->
                        <el-form-item label="重量：" prop="goodsWeight">
                            <el-col :span="8" class="mr-10">
                                <div :class="['flex-items-box', labelColor]">
                                    <el-input type="number" placeholder="请输入商品重量" v-model="ruleForm.goodsWeight" /> （g）
                                </div>
                            </el-col>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </template>
        <!-- 文章图片预览 -->
        <el-dialog v-model="dialogVisible" top="150px" width="30%">
            <img class="dialog-image rounded-4 m-12 mt-20" :src="dialogImageUrl" alt="" />
        </el-dialog>
    </div>
</template>

<!--suppress TypeScriptCheckImport -->
<script setup lang="ts">
import { reactive, ref } from 'vue'
import type {
    FormInstance, FormRules, UploadProps, UploadUserFile
} from 'element-plus'
import { ElMessages, FormRule, timeout } from '@utils/methods'
import { uploadImgURL } from '@/config'
import { HttpResponse } from '@api/http'
import { PageTypeKey } from '@/type/common'
import { useRoute, useRouter } from 'vue-router'
import { cloneDeep } from 'lodash'
import {
    GoodDetailData,
    GoodsClass,
    httpAddGoods,
    httpGoodsClassList,
    httpGoodsDetail,
    httpUpdateGoods
} from '@/api/module/goodsCenter'

// 组件
import RichText from '@jsdawn/vue3-tinymce'
import PageHeader from '@/components/PageHeader/index.vue'
import Icon from '@/components/Icon/index.vue'

// 路由
const { query } = useRoute()
const router = useRouter()

// 页面标题类型
enum PageType {
    'add' = '新增商品',
    'edit' = '编辑商品',
    'see' = '商品详情'
}

// 页面加载
const isLoading = ref(true)

// 页面类型
const pageType = ref<PageTypeKey>()

// 表单是否禁用
const isDisabled = computed(() => pageType.value === 'see')

// 单位颜色
const labelColor = computed(() => (isDisabled.value ? 'text-t-secondary' : 'text-t-title'))

// 商品 id
const goodsId = ref()

// 页面初始化
const pageInit = async () => {
    pageType.value = <PageTypeKey>query.pageType
    // 获取商品分类列表
    httpGoodsClassList().then(async ({ success, data }) => {
        if (success) {
            goodsClassList.value = data ? data.list : []
            switch (query.pageType) {
            case 'add':
                await timeout(500)
                isLoading.value = false
                break
            default:
                goodsId.value = Number(query.goodsId)
                await getGoodsDetail()
            }
        }
    })
}

pageInit()

// 获取商品详情
const getGoodsDetail = () => {
    httpGoodsDetail({ goodsId: goodsId.value }).then(res => {
        const {
            goodsName, goodsDesc, goodsPoints, goodsClassId, goodsImageList,
            goodsDetail, goodsDelivery, isNeedFreight, expressFreight, isLimitBuy,
            limitBuyNum, listingType, listingTime, goodsPrice, goodsStock,
            goodsOriginalPrice, goodsLength, goodsWidth, goodsHeight, goodsWeight
        } = res.data
        ruleForm.goodsName = goodsName
        ruleForm.goodsDesc = goodsDesc
        ruleForm.goodsPoints = goodsPoints
        ruleForm.goodsClassId = goodsClassId
        ruleForm.goodsImageList = goodsImageList
        ruleForm.goodsDetail = goodsDetail
        ruleForm.goodsDelivery = goodsDelivery
        ruleForm.isNeedFreight = Boolean(isNeedFreight)
        ruleForm.expressFreight = expressFreight
        ruleForm.isLimitBuy = Boolean(isLimitBuy)
        ruleForm.limitBuyNum = limitBuyNum
        ruleForm.listingType = listingType
        ruleForm.listingTime = listingTime
        ruleForm.goodsPrice = goodsPrice
        ruleForm.goodsStock = goodsStock
        ruleForm.goodsOriginalPrice = goodsOriginalPrice
        ruleForm.goodsLength = goodsLength
        ruleForm.goodsWidth = goodsWidth
        ruleForm.goodsHeight = goodsHeight
        ruleForm.goodsWeight = goodsWeight
        richTextHeight.value = goodsImageList.length >= 4 ? 540 : 425
    }).finally(async () => {
        await timeout(500)
        isLoading.value = false
    })
}

// 商品配送方式
const deliveryMethods = [
    { label: '上门自提', value: 1 },
    { label: '快递', value: 2 }
]

// 商品分类列表
const goodsClassList = ref<GoodsClass[]>([])

// 表单实例
const ruleFormRef = ref<FormInstance>()

// 表单数据
const ruleForm = reactive<GoodDetailData>({
    goodsName: '',
    goodsDesc: '',
    goodsPoints: '',
    goodsClassId: null,
    goodsImageList: [],
    goodsDetail: '',
    goodsPrice: '',
    goodsStock: '',
    goodsOriginalPrice: '',
    goodsLength: '',
    goodsWidth: '',
    goodsHeight: '',
    goodsWeight: '',
    goodsDelivery: null,
    isNeedFreight: false,
    expressFreight: null,
    isLimitBuy: false,
    limitBuyNum: '',
    listingType: null,
    listingTime: ''
})

// 表单校验
const rules = reactive<FormRules>({
    goodsName: [FormRule.requireRule('请输入商品名称')],
    goodsClassId: [FormRule.requireRule('请选择商品分类', 'change')],
    goodsImageList: [FormRule.requireRule('请上传商品图片')],
    goodsDelivery: [FormRule.requireRule('请选择配送方式', 'change')],
    listingType: [FormRule.requireRule('请选择上架时间', 'change')],
    goodsPrice: [FormRule.requireRule('请输入商品售价')],
    goodsStock: [FormRule.requireRule('请输入商品库存')],
    goodsWeight: [FormRule.requireRule('请输入商品重量')]
})

// 提交表单
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(valid => {
        if (valid) {
            if (ruleForm.isNeedFreight && !ruleForm.expressFreight) {
                ElMessages.warning('请输入运费！')
                return
            }
            if (ruleForm.isLimitBuy && !ruleForm.limitBuyNum) {
                ElMessages.warning('请输入限购量！')
                return
            }
            if (!ruleForm.goodsDetail) {
                ElMessages.warning('请输入商品详情！')
                return
            }
            if (ruleForm.listingType === 2 && !ruleForm.listingTime) {
                ElMessages.warning('请选择上架时间！')
                return
            }
            const params = cloneDeep(ruleForm)
            params.goodsImageList = params.goodsImageList.map((item: UploadUserFile) => ({
                name: item.name,
                url: item.response ? (item.response as Record<string, any>).data : item.url
            }))
            pageType.value === 'add' ? addGoods(params) : editGoods(params)
        }
    })
}

// 添加商品
const addGoods = (goodsInfo: any) => {
    httpAddGoods(goodsInfo).then(({ success }) => {
        if (success) {
            ElMessages.success('新增成功！')
            router.back()
        } else {
            ElMessages.warning('新增失败！')
        }
    })
}

// 编辑商品
const editGoods = (editInfo: any) => {
    const params = {
        ...editInfo,
        goodsId: goodsId.value
    }
    // 更新商品信息
    httpUpdateGoods(params).then(({ success }) => {
        if (success) {
            ElMessages.success('更新成功！')
            router.back()
        } else {
            ElMessages.error('更新失败！请重试！')
        }
    })
}

/**
 * 商品图预览
 * */
// 弹窗图路径
const dialogImageUrl = ref('')

// 弹窗图状态
const dialogVisible = ref(false)

// 预览图片
const handlePictureCardPreview: UploadProps['onPreview'] = uploadFile => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

// 富文本高度
const richTextHeight = ref(410)

// 富文本编辑器
const setting = reactive({
    // 编辑器高度
    height: richTextHeight,
    // 占位内容
    placeholder: '请填写商品详情...',
    // 语言包
    language: 'zh-Hans',
    // 语言包地址
    language_url: 'https://www.jsjserve.top/public/files/language/zh.js',
    // 菜单
    menubar: false,
    // 是否可调节大小
    resize: false,
    // 工具
    toolbar: 'bold italic underline h1 h2 blockquote numlist bullist link image | alignleft aligncenter alignright | removeformat fullscreen',
    // 插件
    plugins: 'codesample link image table lists fullscreen',
    toolbar_mode: 'sliding',
    // 是否只读
    readonly: isDisabled.value,
    // 是否显示 logo
    branding: false,
    // 支持的图片格式
    images_file_types: 'jpeg,jpg,png,gif,bmp,webp',
    forced_root_block: '',
    nonbreaking_force_tab: true,
    link_title: false,
    link_default_target: '_blank',
    content_style: 'body{font-size: 16px}',
    // 开启图片上传模式
    custom_images_upload: true,
    // 图片上传地址
    images_upload_url: uploadImgURL,
    // 图片上传回调
    custom_images_upload_callback: (response: HttpResponse) => response.data
})
</script>

<style lang="less" scoped>
.add-edit-container{
    width: calc(50% - 12px);
}

.specification-logistics{
    height: calc(50% - 12px);
}

.el-form-item--default{
    @apply mb-34;
}

:deep(.el-upload-list__item) {
    width: 120px;
    height: 120px;
}

:deep(.el-upload--picture-card) {
    width: 120px;
    height: 120px;
}

.dialog-image{
    width: calc(100% - 24px);
}
</style>
